(function(root) {

  root.clientId = null;
  root.isCaller = null;
  
  function openChannel(channelToken) {
    console.log('Opening js channel...');
    var channel = new goog.appengine.Channel(channelToken);  
    var handler = {
      'onopen': onChannelOpened,
      'onmessage': onChannelMessage
    };  
    var socket = channel.open(handler);
  };
  
  function onChannelOpened() {
    console.log('Channel opened.');
    
    // Request access to the camera when channel is opened
    root.requestCameraAccess();
  };
  
  function onChannelMessage(event) {
    var message = JSON.parse(event.data);
    console.log('Server->Client message: ', message.type);
    
    if (message.type === 'candidate') {
      root.handleCandidate(message);
    } else if (message.type === 'offer') {
      root.handleOffer(message);
    } else if (message.type === 'answer') {
      root.handleAnswer(message);
    } else if (message.type === 'bye') {
      root.handleBye();
    }   
  };
                                         
  function handleCreatedChannel(event) {
    var response = JSON.parse(event.target.response);
    
    // Server gives back a unique channel token
    var channelToken = response.channelToken;
    
    // And it tells if user is the caller
    root.isCaller = response.isCaller
    
    // This channel token is used to open a js channel
    openChannel(channelToken);
  }
  
  function createChannel() {
    var formData = new FormData();
    var xhr = new XMLHttpRequest();
     
    console.log('Retrieving channel token from server...');
    root.clientId = Math.ceil(Math.random()*10e8);
    
    xhr.open('POST', '/createChannel/');
    formData.append('from', clientId);
    xhr.send(formData);
    xhr.onload = handleCreatedChannel;
  };
  
  window.onload = function() {
    createChannel();
  }
  
})(this);
